package cn.tsinghua.comsmacitccntsinghua.ui;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.media.MediaPlayer;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.telecom.Call;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.zxing.common.StringUtils;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.wonderkiln.camerakit.CameraKitError;
import com.wonderkiln.camerakit.CameraKitEvent;
import com.wonderkiln.camerakit.CameraKitEventListener;
import com.wonderkiln.camerakit.CameraKitImage;
import com.wonderkiln.camerakit.CameraKitVideo;
import com.wonderkiln.camerakit.CameraView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.w3c.dom.Document;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import cn.Port.myserialport.DataUtils;
import cn.Port.myserialport.controll.BoardController;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.tsinghua.comsmacitccntsinghua.DeviceInfo;
import cn.tsinghua.comsmacitccntsinghua.R;
import cn.tsinghua.comsmacitccntsinghua.VO.BinVO;
import cn.tsinghua.comsmacitccntsinghua.VO.status.Status;
import cn.tsinghua.comsmacitccntsinghua.WS.EInfoWebSocketService;
import cn.tsinghua.comsmacitccntsinghua.bean.BaseDataInfo;
import cn.tsinghua.comsmacitccntsinghua.bean.EventReportBean;
import cn.tsinghua.comsmacitccntsinghua.bean.GPSBean;
import cn.tsinghua.comsmacitccntsinghua.bean.HandlerBridge;
import cn.tsinghua.comsmacitccntsinghua.bean.LoginBean;
import cn.tsinghua.comsmacitccntsinghua.bean.WeightBean;
import cn.tsinghua.comsmacitccntsinghua.boardconfig.DustbinStatusControl;
import cn.tsinghua.comsmacitccntsinghua.boardconfig.StartUpControl;
import cn.tsinghua.comsmacitccntsinghua.broadcast.BroadReceiver;
import cn.tsinghua.comsmacitccntsinghua.customview.BinItemView;
import cn.tsinghua.comsmacitccntsinghua.httpservice.API;
import cn.tsinghua.comsmacitccntsinghua.httpservice.HttpUtil;
import cn.tsinghua.comsmacitccntsinghua.model.BannerControl;
import cn.tsinghua.comsmacitccntsinghua.model.CoverControl;
import cn.tsinghua.comsmacitccntsinghua.model.TimeTaskControl;
import cn.tsinghua.comsmacitccntsinghua.tinker.SampleApplicationLike;
import cn.tsinghua.comsmacitccntsinghua.tsinterface.BinStatus;
import cn.tsinghua.comsmacitccntsinghua.tsinterface.IStringResponse;
import cn.tsinghua.comsmacitccntsinghua.utils.AndroidUtil;
import cn.tsinghua.comsmacitccntsinghua.utils.EncodingUtils;
import cn.tsinghua.comsmacitccntsinghua.utils.InternetWatingUtil;
import cn.tsinghua.comsmacitccntsinghua.utils.StringUtil;
import cn.tsinghua.comsmacitccntsinghua.utils.Utils;
import lombok.SneakyThrows;
import okhttp3.HttpUrl;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, BroadReceiver.ObjMessage {

    /* String url1 = "https://image.baidu.com/search/detail?ct=503316480&z=undefined&tn=baiduimagedetail&ipn=d&word=%E7%8E%AF%E4%BF%9D%E5%9B%BE%E7%89%87&step_word=&ie=utf-8&in=&cl=2&lm=-1&st=undefined&hd=undefined&latest=undefined&copyright=undefined&cs=3135045970,569609578&os=2224563473,2618782771&simid=4106075784,604217779&pn=1&rn=1&di=120670&ln=1824&fr=&fmq=1630484086180_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&is=0,0&istype=0&ist=&jit=&bdtype=0&spn=0&pi=0&gsm=0&objurl=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Ffile02.16sucai.com%252Fd%252Ffile%252F2014%252F0917%252F3fccadb7894c474275129617b9a1b8ad.jpg%26refer%3Dhttp%253A%252F%252Ffile02.16sucai.com%26app%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Djpeg%3Fsec%3D1633076083%26t%3D115aa6f6438ebabb62e17f2ea62a8fbe&rpstart=0&rpnum=0&adpicid=0&nojc=undefined";
     String url2 = "https://img1.baidu.com/it/u=1412167690,3476401441&fm=26&fmt=auto&gp=0.jpg";
     String url3 = "https://img2.baidu.com/it/u=1549678844,2900795818&fm=26&fmt=auto&gp=0.jpg";*/
    public static final String TAG = "MainActivity";
    List<BinItemView> binItemViewList = new ArrayList<>();//控制桶子 内有Status
    private String phoneNum;
    private KProgressHUD hud;
    private int showCoverTime = 3 * 60 * 1000;//单位毫秒
    private EditText etPhone;
    private Button login;
    private RelativeLayout rlMask, rlBannerParent;
    private RelativeLayout rlLoginTip;//登录提示
    private RelativeLayout rlLoginInput;
    private LinearLayout needIdLayout;//手机号码登录
    private RelativeLayout rlMoneyAndCount;//环保币和投放次数
    private TextView tvMoney, tvCount, tvLoginState, tvHeadState, tvCountDown, tvNoLoginCountDown;
    private ImageView iv_headportrait;
    private Button login_button, login_id_button;
    private Button log_out_btn;//完成投递并退出登录
    private BGABanner mContentBanner;//顶部轮播图
    private BGABanner coverBanner;//封面轮播图
    private BannerControl topBannerControl;
    private CoverControl coverControl;
    private BoardController boardController;
    private DustbinStatusControl dustbinStatusControl;
    private BroadReceiver broadReceiver;
    private StartUpControl startUpControl;//登录成功后 初始化底层参数  控制
    private Map map;
    private Gson gson;
    private LoginBean loginBean;
    private TimeTaskControl timer;
    private BaseDataInfo baseDataInfo;
    private List<BaseDataInfo.DataBean.BannerBean> bannerData;
    private List<BaseDataInfo.DataBean.CoverBean> coverData;

    private Button update;


    private boolean haveLogin = false; //标志用户登录状态
    private boolean noIdhaveLogin = false;
    /**
     * 重构haveLogin，由于网络可能卡顿,因此除了"未登录","已登录",
     * 加入"登陆中"
     * -1未登录 0已登录 1登陆中
     * 主要控制刷卡
     */
    private int loginStatus = -1;

    private Boolean canSendNoIdLoginNotice = true;
    //发送通知底层可开门的Timer 限制一秒智能开一次
    private Timer noIdLoginTimer = new Timer();

    private HandlerBridge handlerBridge = HandlerBridge.getInstance();//Handler桥接到Receiver去好发送消息
    private TextView tvDustbinOnState;
    private ImageView ivDustbinOne;
    private TextView tvDustbinTwoState;
    private ImageView ivDustbinTwo;
    private TextView tvDustbinThreeState;
    private ImageView ivDustbinThree;
    private TextView tvDustbinFourState;
    private ImageView ivDustbinFour;
    private LinearLayout binCombination1;
    private LinearLayout binCombination2;
    private LinearLayout binCombination3;
    private LinearLayout binCombination4;
    private TextView tvDustbinTip;  //需要gone掉的120秒自动
    private TextView tvLoginInput; //需要gone掉的提示
    private CameraView reluctant_photo_camera;

    private LinearLayout dustbinParent;//垃圾桶的父布局

    private Button backtoChoose; //返回选择界面

    //testControllerId
    private TextView testControllerId;

    //播放语音
    private MediaPlayer mediaPlayer = new MediaPlayer();

    //设备初始化次数
    int deviceInitTime = 0;

    //太阳码和配置码
    private ImageView ivWX;

    ////标志此时是QR 如果是QR那么就换成太阳
    private boolean isQR = false;

    //投口
    String popWindowContent = "";
    TextView throwRes;

    //机器状态位
    boolean hasRepair = true;

    //刚启动置5秒不能操作
    boolean firstStart = true;

    /**PopUpWindow里面的内容**/
    private TextView popText;
    PopupWindow pW;

    //GPS位置
    GPSEntity gpsEntity = new GPSEntity();
    LocationManager locationManager = null; //经纬度
    LocationListener locationListener = null;//监听器

    //请求开门保障 强制要求一用户只有一次开门权限
    int haveSendOpenDoor = -1;// -1未送 0已送 //TODO 写一下逻辑

    //调用Service内的方法
    EInfoWebSocketService.LocalBinder localBinder;

    //开启Service的Connection
    Intent WSintent;

    //读取流量信息的次数控制
    int writeFileClock = 0;

    //可开门的控制Timer
//    Timer timerDoorOpen;
    Boolean haveCanOpenStatus = false;
//    int sendTimes = 0;//折中的办法，发三十次

    public Handler handler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @SneakyThrows
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
                switch (msg.what) {
                case 0x30://登录后的自动退出
                    tvCountDown.setText(msg.getData().getLong("time") / 1000 + "秒后退出登录");
                    break;
                case 0x31: //无id登录后的自动退出
                    tvNoLoginCountDown.setText(msg.getData().getLong("time") / 1000 + "秒后退出登录");
                    break;
                case 0x20://登出
                    loginOut();
                    break;
                case 0x40://扫码获取手机号登录
                    Login();
                    break;
                case 0x10:// 登录成功后的操作
                    closeHud();
                    //登录成功
                    loginStatus2HaveIdLogin();
                    if (haveLogin == true && noIdhaveLogin == false && (loginStatus == -1 || loginStatus == 0) ) { //若已登录 则不传
                        dustbinStatusControl.loginNotice();//登录成功 通知底层
                    }else {
                        return;
                    }
                    loginUI();
                    if (haveLogin == false) {
                        timer.startTimer();
                    }
                    haveLogin = true;
                    DeviceInfo.customerId = loginBean.getData().getCustomerId();
                    break;
                case 0x11: //fake登录
                    fakeLogin();
                    break;
                case 1://封面显示控制
                    rlMask.setVisibility(View.VISIBLE);
                    /**  暂时取消
                     baseDataInfo.getData().getDevice();
                     //启动初始化封面
                     coverData = baseDataInfo.getData().getCover();
                     if (null!=coverData){
                     coverBannerInit(coverData);
                     }**/
                    break;
                case 2://网络连接成功 基础数据处理
                    baseDataInfo = DeviceInfo.getBaseDataInfo();
                    if (null != baseDataInfo && null != baseDataInfo.getData()) {
                        bannerData = baseDataInfo.getData().getBanner();
                        if (null != bannerData) {
                            //启动顶部轮播图
                            topBannerInit(bannerData);
                        }
                        //板子初始化数据
                        startUpControl.sendToBoardInitData(baseDataInfo.getData().getDevice());
                        //开启封面
                        startCover();
                        //设备状态定时上传
                        timer.startDeviceStatusTimer();
                        //页面桶子数据
                        setBinItemsImageStatus();
                        Log.d("发送可开门","s");
                        Timer doorOpenStatusTimer = new Timer();
                        TimerTask doorOpenStatusTimerTask = new TimerTask() {
                            @Override
                            public void run() {
                                boardController.getCanOpenDoor();
                            }
                        };
                        doorOpenStatusTimer.schedule(doorOpenStatusTimerTask,5*1000);
                        Log.d("MainActivity","handler case2 网络连接成功");
                    }
                    //开启websocket的Service
                    /**
                    WSintent = new Intent(MainActivity.this,EInfoWebSocketService.class);
                    startService(WSintent);**/
//                    serviceCon = new ServiceCon();//用来调用Service内的内容
//                    bindService(intent,serviceCon,BIND_AUTO_CREATE);
                    break;
                case 20://网络连接失败的基础数据处理
                    setBinItemsImageStatus();
                    dustbinParent.setBackground(getApplication().getDrawable(R.mipmap.netf));
                    Log.d("MainActivity","handler case20 网络连接成功");
                    break;
                case 200012://返回投口总重
                    break;
                case 200014://投口状态获取
                    break;
                case 200016://箱内温度获取
                    break;
                case 200018://警报信息
                    break;
                case 200019://电机异常
//                    HttpUtil.warnReport(MyApplication.deviceId);
                    break;
                case 200020://控制板ID
                    break;
                /**网络请求处理**/
                case 300001://http设备状态
                    HttpUtil.equipmentStatus();
                    break;
                case 300002://登出请求
                    //投递数据送上去
                    break;
                case 300003://重发BaseData请求
                    break;
                case 300004:
                    //请求数据
//                    requestBaseData();
                    showHud();
                    HttpUtil.getDeviceInfo(DeviceInfo.boardId);
                    break;
                    //此处已经拿到GPS
                case 300005:
                    sendGPS(gpsEntity);
                    break;
                case 300006://修改底下状态栏的状态
                    Bundle bundle = msg.getData();
                    int index = bundle.getInt("index");
                    int type = bundle.getInt("type");
                    Status status = new Status();
                    status.setType(type);
                    DeviceInfo.getBinVOSList().get(index).getBinItemView().setStatus(status);
                    break;
            }
        }
    };

    /**
     * 测试账号：18206285385
     * @param savedInstanceState
     */
    private String testPhone = "18206285385";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
        setContentView(R.layout.activity_main);
        init();
        EventBus.getDefault().register(MainActivity.this);
        //网络请求初始化
        API.init();

        //获取控制板ID
        Toast.makeText(MainActivity.this, "主板初始化", Toast.LENGTH_SHORT).show();
        //延时一个s让波特率稳定
        Timer Bottimer = new Timer();
        dustbinStatusControl.getBoardId();
        boardController.getCanOpenDoor();
//        TimerTask BottimerTask = new TimerTask() {
//            @Override
//            public void run() {
//            }
//        };
//        Bottimer.schedule(BottimerTask, 1500);
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                firstStart = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "初始化完成", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };

        timer.schedule(timerTask, 5000);
        //定时重启
        Timer rebootTimer = new Timer();
        TimerTask rebootTimerTask = new TimerTask() {
            @Override
            public void run() {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                if (hour == 2 && minute == 58) {
                    boardController.reboot();
                    //https://gitee.com/estaryjl/com.estar.intele
                }
            }
        };


        rebootTimer.schedule(rebootTimerTask, 0, 60 * 1000);//一分钟执行一次
        //获取定位
        GPSEntity gpsEntity = GPSUtil(getApplicationContext());
//        sendGPS(gpsEntity);

        //如果是可回收投口，则给出提示
        if(DeviceInfo.mouthQuantity == 5){
            login_button.setVisibility(View.GONE);
            tvDustbinTip.setText(this.getString(R.string.recovery_tip));
        }
        Log.e("MainActivityRun","Oncreate");
        //流量监测
        Timer DataTimer = new Timer();
        TimerTask DataTimerTask = new TimerTask() {
            @Override
            public void run() {
                //TODO  获取UID写入
                String uid = AndroidUtil.getUID(getApplicationContext());
                Log.e("UIDDDD",uid);
                Long dataCount = InternetWatingUtil.getAppTotalData(10055);
                Double Ddata = Double.parseDouble(String.valueOf(dataCount))/1000;
                Date date = new Date();
                writeFileClock++;
                if(writeFileClock == 20){
                   InternetWatingUtil.writeFile(String.valueOf(Ddata) + "KB  时间: " + String.valueOf(date.getHours()) + ":" + date.getMinutes()+ ":" + date.getSeconds() + "\r\n");
                   writeFileClock = 0;
                }
                Log.d("dataaaaaaaaa", Ddata+ "KB  时间: " + String.valueOf(date.getHours()) + ":" + date.getMinutes()+ ":" + date.getSeconds());
            }
        };
        DataTimer.schedule(DataTimerTask,0,1000);

    }




    private void sendGPS(GPSEntity gpsEntity){

        Timer timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                if(null != DeviceInfo.getDeviceId()){

                    GPSBean gpsBean = new GPSBean();

                    gpsBean.setDeviceId(DeviceInfo.getDeviceId());

                    gpsBean.setLongitude(String.valueOf(gpsEntity.getLongitude()));

                    gpsBean.setLatitude(String.valueOf(gpsEntity.getLatitude()));

                    HttpUtil.GPSInfo(gpsBean);

                    timer.cancel();

                }

            }

        };

        timer.schedule(timerTask,0,1000);

    }


    private void closeHud() {
        if (null != hud && hud.isShowing()) {
            hud.dismiss();
        }
    }

    private void showHud() {
        if (hud == null) {
            hud.show();
        }

        CountDownTimer countDownTimer = new CountDownTimer(20 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (hud.isShowing()) {
                            Toast.makeText(MainActivity.this, "机器异常，请联系管理员。", Toast.LENGTH_SHORT).show();
                            hud.dismiss();
                        }
                    }
                });
            }
        };
        countDownTimer.start();
    }


    //初始化顶部轮播图
    private void topBannerInit(List<BaseDataInfo.DataBean.BannerBean> data) {
        topBannerControl = new BannerControl(MainActivity.this, mContentBanner);
        topBannerControl.setData(data);
        topBannerControl.onClickListener();
    }

    /**
     * 启动遮罩层广告轮播图
     */
    private void startCover() {

        Message message = Message.obtain();
        message.what = 1;
        handler.sendMessageDelayed(message, showCoverTime);
    }

    /**
     * 初始化封面轮播图
     */
    private void coverBannerInit(List<BaseDataInfo.DataBean.CoverBean> data) {
        coverControl = new CoverControl(MainActivity.this, coverBanner);
        coverControl.setData(data);
        coverControl.onClickListener();
    }

    private void init() {
        map = new HashMap();
        gson = new Gson();
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setWindowColor(getResources().getColor(R.color.loginbg))
                .setAnimationSpeed(2);
        timer = new TimeTaskControl(getApplicationContext(), handler);
        initBoardP();
        startUpControl = new StartUpControl(getApplicationContext(), boardController);
        coverBanner = findViewById(R.id.coverBanner);
        tvCountDown = findViewById(R.id.tvCountDown);
        tvNoLoginCountDown = findViewById(R.id.tv_noLogin_CountDown);
        iv_headportrait = findViewById(R.id.iv_headportrait);
        tvHeadState = findViewById(R.id.tvHeadState);
        tvLoginState = findViewById(R.id.tvLoginState);
        tvCount = findViewById(R.id.tvCount);
        tvMoney = findViewById(R.id.tvMoney);
        etPhone = findViewById(R.id.etPhone);
        login = findViewById(R.id.login);
        login.setOnClickListener(this);
        mContentBanner = findViewById(R.id.banner_guide_content);
        rlBannerParent = findViewById(R.id.rlBannerParent);
        log_out_btn = findViewById(R.id.log_out_btn);
        log_out_btn.setOnClickListener(this);
        rlMask = findViewById(R.id.rlMask);
        rlMask.setOnClickListener(this);
        rlLoginTip = findViewById(R.id.rlLoginTip);
        rlLoginInput = findViewById(R.id.rlLoginInput);
        needIdLayout = findViewById(R.id.needid_layout);
        rlMoneyAndCount = findViewById(R.id.rlMoneyAndCount);
        login_button = findViewById(R.id.login_button);
        login_button.setOnClickListener(this);
        login_id_button = findViewById(R.id.login_needid_button);
        login_id_button.setOnClickListener(this);
        tvDustbinOnState = findViewById(R.id.tvDustbinOnState);
        ivDustbinOne = findViewById(R.id.ivDustbinOne);

        tvDustbinTwoState = findViewById(R.id.tvDustbinTwoState);
        ivDustbinTwo = findViewById(R.id.ivDustbinTwo);
        tvDustbinThreeState = findViewById(R.id.tvDustbinThreeState);
        ivDustbinThree = findViewById(R.id.ivDustbinThree);
        tvDustbinFourState = findViewById(R.id.tvDustbinFourState);
        ivDustbinFour = findViewById(R.id.ivDustbinFour);
        tvDustbinTip = findViewById(R.id.tvDustbinTip);
        tvLoginInput = findViewById(R.id.tvLoginInput);
        backtoChoose = findViewById(R.id.backtoChoose);
        backtoChoose.setOnClickListener(this);
        testControllerId = findViewById(R.id.testControllerId);
        ivWX = findViewById(R.id.ivWX);
        throwRes = findViewById(R.id.throwRes);
        dustbinParent = findViewById(R.id.llDustbin);
        binCombination1 = findViewById(R.id.bin_combination_1);
        binCombination2 = findViewById(R.id.bin_combination_2);
        binCombination3 = findViewById(R.id.bin_combination_3);
        binCombination4 = findViewById(R.id.bin_combination_4);
        update = findViewById(R.id.update);
        update.setOnClickListener(this);
        update.setVisibility(View.GONE);
//        //模拟添加四个组件
//        BinItemView binItemView = new BinItemView(getApplicationContext());
//        //设置样式和图片这些基本属性
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
//        lp.bottomMargin = 100;
//        lp.weight = 1;
//        binItemView.setLayoutParams(lp);
//        binItemView.setStatus(new Status(Status.NORMAL,Status.normal_not_full));
//        binItemView.setBinImageBitMap(R.mipmap.green_close);
//        //TODO 最终是由底层板子->Status设置桶子的状态(图片)->http上去
//        String url = "https://www.ai-dustbin.com/group1/M00/00/01/rBlUB2E8RzGACfYoAAFXok9rxBg140.jpg";
//        binItemView.setNetDrawable(url);
//        binItemViewList.add(binItemView);
//        dustbinParent.addView(binItemView);
        //原来的4个Gone掉
        setoriginBinGone();

//        reluctant_photo_camera = findViewById(R.id.reluctant_photo);
//        reluctant_photo_camera.addCameraKitListener(new CameraKitEventListener() {
//            @Override
//            public void onEvent(CameraKitEvent cameraKitEvent) {
//
//            }
//
//            @Override
//            public void onError(CameraKitError cameraKitError) {
//
//            }
//
//            @Override
//            public void onImage(CameraKitImage cameraKitImage) {
//                //上传图片
//            }
//
//            @Override
//            public void onVideo(CameraKitVideo cameraKitVideo) {
//
//            }
//        });

    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    //初始化底层相关参数
    private void initBoardP() {
        handlerBridge.setHandler(handler);
        broadReceiver = new BroadReceiver(baseDataInfo, handler);
        //动态注册Message
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.intent.board");
        registerReceiver(broadReceiver, filter);
        broadReceiver.setObjeMessage(this);

        boardController = new BoardController(MainActivity.this);
        dustbinStatusControl = new DustbinStatusControl(getApplicationContext(), boardController);
        dustbinStatusControl.getBoardId();

    }

    @Override
    public void onClick(View v) {
        startCover();//有任何点击则重置
        if (firstStart) { //首次启动等待五秒初始化
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "首次启动初始化，请稍等", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            hintKeyBoard();//有任何操作都关闭软键盘
            rlMask.setVisibility(View.GONE);
            switch (v.getId()) {
                case R.id.rlMask:
                    rlMask.setVisibility(View.GONE);
                    handler.removeMessages(1);
                    break;
                case R.id.login:
                    phoneNum = etPhone.getText().toString();
                    if (!StringUtil.isEmptyStr(phoneNum)) {
                        Toast.makeText(getApplicationContext(), "请输入手机号", Toast.LENGTH_SHORT).show();
                    } else {
                        Login();
                    }
                    break;
                case R.id.login_button:
                    if (haveLogin || loginStatus == 0 || loginStatus == 1) { //扫码 已登录/登陆中 则不进入无登录使用
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "请完成投递再点击无登录使用", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        //二次控制 只有未登录才给进
                        if(loginStatus == -1 && canSendNoIdLoginNotice){
                            canSendNoIdLoginNotice = false;
                            noIdLoginUI();
                            //此处直接发送登录 游客状态 允许打开
                            timer.startNoIdTimer();
                            boardController.userLogin();
                            playHeadMedia();
                            loginStatus2NoIdLogin();
                            TimerTask timerTask = new TimerTask() {
                                @Override
                                public void run() {
                                    canSendNoIdLoginNotice = true;
                                }
                            };
                            noIdLoginTimer.schedule(timerTask,1000);
                        }

                    }
                    break;
                case R.id.log_out_btn://完成投递并退出
                    timer.endTimer();
                    //清除登录状态
                    loginstatus2Logout();
                    handler.sendEmptyMessage(0x20);
                break;
                case R.id.login_needid_button: //需要账号登录
                    rlLoginTip.setVisibility(View.GONE);
                    needIdLayout.setVisibility(View.VISIBLE);
                    rlLoginInput.setVisibility(View.VISIBLE);
                    tvLoginInput.setVisibility(View.GONE);
                    tvNoLoginCountDown.setVisibility(View.GONE);
                    break;
                case R.id.backtoChoose:
                    afterPhoneLoginBack();//回到起始状态
                    break;
                case R.id.update:
                    Log.d("path",Environment.getExternalStorageDirectory().getAbsolutePath());
                    TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), Environment.getExternalStorageDirectory().getAbsolutePath()+"/patch_signed_7zip.apk");
                    break;
            }
        }

    }

    private void afterPhoneLoginBack() {//手机号登录成功
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rlLoginTip.setVisibility(View.VISIBLE);
                needIdLayout.setVisibility(View.GONE);
                rlLoginInput.setVisibility(View.GONE);
                tvLoginInput.setVisibility(View.VISIBLE);
                tvNoLoginCountDown.setVisibility(View.VISIBLE);
                etPhone.setText("");
            }
        });
    }

    //退出登录
    private void loginOut() {
        rlMoneyAndCount.setVisibility(View.GONE);
        log_out_btn.setVisibility(View.GONE);
        log_out_btn.setVisibility(View.GONE);
        rlLoginTip.setVisibility(View.VISIBLE);
        rlLoginInput.setVisibility(View.GONE);
        tvLoginState.setText("欢迎使用");
        tvHeadState.setText("未登录");
        etPhone.setText("");
        tvHeadState.setBackground(getResources().getDrawable(R.drawable.button_shape));
//        iv_headportrait.setBackground(getResources().getDrawable(R.mipmap.envip));
        iv_headportrait.setImageResource(R.mipmap.envip);
        dustbinStatusControl.logOutNotice();//退出成功 通知底层
        haveLogin = false; //用户登录状态
        noIdhaveLogin = false;
        loginStatus = -1;//未登录
//        noIdhaveLogin = false;
        hintKeyBoard();
        playTailMedia();
    }

    //TODO 之后删除的FakeLogin
    private void FakeLogin() {
        handler.sendEmptyMessage(0x11);
    }


    private void Login() {
        loginStatus = 1;//登陆中
        rlMask.setVisibility(View.GONE); //海报消失
        //若已登录 则不做动作
        if (haveLogin == true) {
            refreshTimer();//如果已登录刷新一下timer
            return;
        }
        refreshTimer();
        if (!StringUtil.isEmptyStr(phoneNum)) {
            phoneNum = testPhone;
        }
        SampleApplicationLike.saveData("phone", phoneNum);
        showHud();
        new Thread(new Runnable() {
            @Override
            public void run() {
                map.clear();
                map.put("card_number", phoneNum);
                map.put("deviceId", DeviceInfo.deviceId);
                API.scanCodeCertification(map, new IStringResponse() {
                    @Override
                    public void onSuccess(String result) {
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        if (jsonObject.getString("err_code").equals("1")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "无此用户,请注册", Toast.LENGTH_SHORT).show();
                                    closeHud();
                                }
                            });
                            loginStatus = -1;
                        } else {
                            //登录成功
                            haveLogin = true;
                            loginStatus = 0;
                            loginBean = gson.fromJson(result, LoginBean.class);
                            Message message = Message.obtain();
                            message.what = 0x10;
                            afterPhoneLoginBack();//把gone掉的组件visible回来
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //关闭软键盘
                                    hintKeyBoard();
                                    etPhone.setText("");//设置手机号码为空
                                }
                            });
                            playHeadMedia();
                            handler.sendMessage(message);

                        }

                    }
                    @Override
                    public void onFail(int statusCode) {
                        loginStatus = -1;//未登录
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                closeHud();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }).start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        handler.removeMessages(1);
        startCover();
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //从板子查看桶子的可开状态

        handler.removeMessages(1);
        Log.e("MainActivityRun","OnResume");
        startCover();
    }

    @Override
    protected void onPause() {
//        if(reluctant_photo_camera.isStarted()){
//            reluctant_photo_camera.stop();
//        }
        super.onPause();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(String str) {
        //完成了获取baseDataInfo  请求成功
        switch (str){
            case "finish_server_data":
                //更新UI
                closeHud();
                handler.sendEmptyMessage(2);
                //开启服务
                break;
            case "finish_server_data_error":
                closeHud();
                handler.sendEmptyMessage(20);
                Toast.makeText(MainActivity.this, "网络连接失败，请联系管理员。", Toast.LENGTH_SHORT).show();
                break;
            case "noRegister":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "设备未注册", Toast.LENGTH_SHORT).show();
                        //这里表明确实未注册生成QR 二次保障
                        SampleApplicationLike.saveData("hasConfiguration", "0");//置为未注册
                        setconfigurationQR();
                    }
                });
            case  "sopCHud":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeHud();
//                    MyApplication.saveData("hasConfiguration","0");//置为未注册
                        setconfigurationQR();
                        Toast.makeText(MainActivity.this, "网络连接失败，请联系管理员。", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case "noIdRetri":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "投递成功", Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case "BoardRepair":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setBottomTextNormal();
                    }
                });
                break;

            case "machineError":
                //机器异常
                hasRepair = false; //出错
                setBottomTextError();
                break;
            case "machineRepair":
                if (!hasRepair) {
                    setBottomTextNormal();
                }
                hasRepair = true; //已修复
                break;
            case "GPSSuccess":
                //TODO 停止监听
                if(null!=locationListener && null !=locationManager){
                    locationManager.removeUpdates(locationListener);
                }
                break;
            case "fileRecSuc":
                reLoadApp();
                break;

            case "doorCanOpenStatusSuccess":
                haveCanOpenStatus = true;
//                timerDoorOpen.cancel();
                break;
        }
    }


    //关闭软键盘
    public void hintKeyBoard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


    private void setBottomTextError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvDustbinOnState.setText("异常");
                tvDustbinTwoState.setText("异常");
                tvDustbinThreeState.setText("异常");
                tvDustbinFourState.setText("异常");
                tvDustbinOnState.setBackgroundResource(R.drawable.bin_lost_status_shape);
                tvDustbinTwoState.setBackgroundResource(R.drawable.bin_lost_status_shape);
                tvDustbinThreeState.setBackgroundResource(R.drawable.bin_lost_status_shape);
                tvDustbinFourState.setBackgroundResource(R.drawable.bin_lost_status_shape);
            }
        });

    }

    private void setBottomTextNormal() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvDustbinOnState.setText("正常");
                tvDustbinTwoState.setText("正常");
                tvDustbinThreeState.setText("正常");
                tvDustbinFourState.setText("正常");
                tvDustbinOnState.setBackgroundResource(R.drawable.bin_status_shape);
                tvDustbinTwoState.setBackgroundResource(R.drawable.bin_status_shape);
                tvDustbinThreeState.setBackgroundResource(R.drawable.bin_status_shape);
                tvDustbinFourState.setBackgroundResource(R.drawable.bin_status_shape);
            }
        });

    }
//testtttttt



    private void sendMsg(int what, Bundle bundle) {
        Message message = Message.obtain();
        message.what = what;
        if (!haveLogin) {
            handler.sendMessage(message);
        }
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void getObject(Object o) {
        /**所有信号都要经这里处理**/
        //WeightBean给到后端
        if (o.getClass().equals(WeightBean.class)) {
            final WeightBean weightBean = (WeightBean)o;
             //垃圾桶内的数量
            popWindowContent = generatePushTip(weightBean);
//            for (int i = 0; i < binNum; i++) {
//                popWindowContent = popWindowContent + String.valueOf(i + 1) + "号投口" + ((double) weightBean.getDetail().get(i).getQuality()) / 1000 + "kg\n\n";
//            }
            popWindow(popWindowContent);
            weightBean.setDeviceId(DeviceInfo.deviceId);
            weightBean.setCustomerId(DeviceInfo.customerId);
            if(baseDataInfo !=null){
                try {//如果baseDatainfo为空则需要处理一下
                    for (int i = 0; i < 4; i++) {
                        weightBean.getDetail().get(i).setInner_number(safe_weightBeangetInnerNumber(baseDataInfo, i));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                HttpUtil.retrieveRes(weightBean);
            }else {
                showToast("设备联网失败，请联系管理员。");
            }
        }

        if (o.getClass().equals(String.class)) {
            String Code = String.valueOf(o);
            if (Code.equals("deviceId")) {//请求deviceId
//                HttpUtil.getDeviceInfo(MyApplication.boardId);
                handler.sendEmptyMessage(300004);
                testControllerId.setText("No." + DeviceInfo.boardId);
//                setconfigurationQR();
            }
        }

        //处理hash 各种预警
        if (o.getClass().equals(HashMap.class)) {
            HashMap<String, List<String>> hashMap = (HashMap<String, List<String>>) o;
            if (hashMap.containsKey("warn")) {
                List<String> warnInfo = hashMap.get("warn"); //这里的full预留给报警上传
                //控制UI
                warnText(warnInfo.get(0),warnInfo.get(1),warnInfo.get(2));
                //传到后端
                EventReportBean eventReportBean = warn2ServerContent(warnInfo);
                HttpUtil.eventReport(DeviceInfo.deviceId, eventReportBean);
            } else if (hashMap.containsKey("mouth")) { //废弃 没有意义
//                String[] mouthInfo = hashMap.get("mouth");
//                setBinImage(mouthInfo);
            } else if (hashMap.containsKey("id")) {
                if (noIdhaveLogin){
                    showToast("请完成投递再点击无登录使用");
                }else{
                    handler.removeMessages(1);
                    startCover(); //重新计时
                    List<String> id = hashMap.get("id");
                    phoneNum = id.get(0);
                    if (phoneNum.startsWith("4")) {
                        FakeLogin();
                    } else {
                        if (!haveLogin && loginStatus == -1) { //只有在未登录状态下才转换成登录状态
                            sendMsg(0x40, new Bundle());
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MainActivity.this, "请勿重复登录", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                }
            } else if (hashMap.containsKey("mortorerror")) {
                /**
                 * error eg. :
                 * 01 01 01 01 00 00 00 00
                 */
                List<String> error = hashMap.get("mortorerror"); //这里的full预留给报警上传
                //UI显示
                errorText(error);
                //{55，00}
                if(baseDataInfo != null){
                    HttpUtil.warnReport(DeviceInfo.getDeviceId(), error, baseDataInfo);
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showToast("设备联网失败，请联系管理员");
                        }
                    });
                }
            }else if (hashMap.containsKey("doorStatus")){
                List<String> openDoorStatus = hashMap.get("doorStatus");
//                List<Status> statusList = doorOpenStatus(openDoorStatus);
                doorOpenStatus(openDoorStatus);
//                EventBus.getDefault().post("doorCanOpenStatusSuccess");
            }
        }
    }

    private String generatePushTip(WeightBean weightBean){
        int binNum = weightBean.getDetail().size();
        String res = "";
        if(binNum == 4){
            for (int i = 0; i < binNum; i++) {
                res = res + String.valueOf(i + 1) + "号投口" + ((double) weightBean.getDetail().get(i).getQuality()) / 1000 + "kg\n\n";
            }
        }else if(binNum == 5) {
            res = res + "纸类投口" + ((double) weightBean.getDetail().get(0).getQuality()) / 1000 + "kg\n\n";
            res = res + "塑料投口" + ((double) weightBean.getDetail().get(1).getQuality()) / 1000 + "kg\n\n";
            res = res + "金属投口" + ((double) weightBean.getDetail().get(2).getQuality()) / 1000 + "kg\n\n";
            res = res + "玻璃投口" + ((double) weightBean.getDetail().get(3).getQuality()) / 1000 + "kg\n\n";
            res = res + "织物投口" + ((double) weightBean.getDetail().get(4).getQuality()) / 1000 + "kg\n\n";
        }
        return res;
    }

    /**
     * 生成一个有完全数据的binVO
     * @return
     */
    private BinVO generateBinVO(BaseDataInfo.DataBean.DeviceInListBean device,int index){
//        List<Status> statusList = DeviceInfo.getStatusList();
        BinVO binVO = new BinVO();
        BinItemView binItemView = new BinItemView(getApplicationContext());
        binVO.setPicURL(device.getPicUrl().toString());
        binVO.setInner_order(device.getInner_order());
        binVO.setIndex(index);
        //http拿到图片然后设置图片
        Log.d(TAG,"generateBinVO ----- 设置图片");
        binItemView.setNetDrawable(binVO.getPicURL());
        binVO.setBinItemView(binItemView);
        Status status = new Status(Status.NORMAL,Status.normal_not_full);
        status.setWeight(0);
        binVO.getBinItemView().setStatus(status);
        return binVO;
    }

    /**
     * 非联网状态下生成List内，防止List为空
     * @param content
     */



    public void popWindow(final String content) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop_quality, null);
                pW = new PopupWindow(contentView, 600, 350, true);

                popText = contentView.findViewById(R.id.throwRes);
                popText.setText(content);
                pW.setBackgroundDrawable(new BitmapDrawable());
                pW.setOutsideTouchable(true);
                pW.setContentView(contentView);
                View rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
                pW.showAtLocation(rootView, Gravity.CENTER, 0, 0);
                contentView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pW.dismiss();
                            }
                        });
                    }
                });

                TimerTask timerTask = new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                pW.dismiss();
                            }
                        });
                    }
                };
                Timer timer = new Timer();
                timer.schedule(timerTask, 3000);
            }
        });
    }


    //刷新timer
    public void refreshTimer() {
        timer.endTimer();
        timer.startTimer();
    }

    //显示出配置二维码
    //TODO 存在问题
    public void setconfigurationQR() {
        String s = SampleApplicationLike.getStrData("hasConfiguration");
        if (s == null || s.equals("") || s == "" || s.equals("0") || s == "0") {//未被配置 设置QRCode
            Bitmap qrCodeBitmap = EncodingUtils.createQRCode(DeviceInfo.getBoardId(), 290, 290, null);
            ivWX.setImageBitmap(qrCodeBitmap);
            ivWX.setBackgroundResource(R.mipmap.xcxm);
            SampleApplicationLike.saveData("hasConfiguration", "1");
            isQR = true;
            //重新请求一下deviceId 实现自动修复
        } else if (s.equals("1") || s == "1") {
            if (isQR == true) {
                ivWX.setImageResource(R.mipmap.xcxm);
            }
        }
    }

    //设置垃圾桶图片
    @Deprecated
    public void setBinImage(String[] mouthInfo) {
        if (mouthInfo[0].equals("10")) {
            ivDustbinOne.setBackgroundResource(R.mipmap.green_close);
        } else if (mouthInfo[0].equals("01")) {
            ivDustbinOne.setBackgroundResource(R.mipmap.green_open);
        }
        if (mouthInfo[1].equals("10")) {
            ivDustbinTwo.setBackgroundResource(R.mipmap.blue_close);
        } else if (mouthInfo[1].equals("01")) {
            ivDustbinTwo.setBackgroundResource(R.mipmap.blue_open);
        }

        if (mouthInfo[1].equals("10")) {
            ivDustbinThree.setBackgroundResource(R.mipmap.yellow_close);
        } else if (mouthInfo[1].equals("01")) {
            ivDustbinThree.setBackgroundResource(R.mipmap.yellow_open);
        }

        if (mouthInfo[1].equals("10")) {
            ivDustbinFour.setBackgroundResource(R.mipmap.red_close);
        } else if (mouthInfo[1].equals("01")) {
            ivDustbinFour.setBackgroundResource(R.mipmap.red_open);
        }

    }

    //播放开始音乐
    private void playHeadMedia() {
        mediaPlayer.reset();
        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.head);
        mediaPlayer.start();
    }

    //播放结束音乐
    private void playTailMedia() {
        mediaPlayer.reset();
        mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.tail2);
        mediaPlayer.start();
    }


    @Override
    protected void onDestroy() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                closeHud();
            }
        });
        EventBus.getDefault().unregister(this);
        unregisterReceiver(broadReceiver);
        //TODO 暂时关闭此Service,调试完成重新打开
//        stopService(WSintent);
//        unbindService(serviceCon);//解绑Service
        super.onDestroy();
    }


    //获得预警Bean的内容
    public EventReportBean warn2ServerContent(List<String> info) { //警报
        boolean normal = true; //不正常置底text为红色
        EventReportBean eventReportBean = new EventReportBean();
        String[] full = getRealBinary(info.get(0));
        String[] tempe = getRealBinary(info.get(1));
        String[] smoke = getRealBinary(info.get(2));
        String fullStatus = "", tempeStatus = "", smokeStatus = "";
        if (baseDataInfo == null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "主板连接异常，请联系管理员", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            try {
                for (int i = 0; i < full.length; i++) {
                    BaseDataInfo.DataBean dataBean = baseDataInfo.getData();
                    List<BaseDataInfo.DataBean.DeviceInListBean> deviceBeanList = dataBean.getDeviceInList();
                    if (deviceBeanList.size() == 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "获取设备内桶信息异常，请联系管理员", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    BaseDataInfo.DataBean.DeviceInListBean deviceInListBean = deviceBeanList.get(i);
                    int inner_number = deviceInListBean.getInner_order();
//                    int inner_number = baseDataInfo.getData().getDeviceInList().get(i).getInner_order();
                    if (full[i] == "1") {
                        normal = false;
                    }
                    fullStatus = fullStatus + inner_number + "-" + full[i] + ",";
                    if (i == fullStatus.length() - 1) {
                        fullStatus = fullStatus + inner_number + "-" + full[i];
                    }
                }
                for (int i = 0; i < tempe.length; i++) {
                    int inner_number = baseDataInfo.getData().getDeviceInList().get(i).getInner_order();
                    tempeStatus = tempeStatus + inner_number + "-" + tempe[i] + ",";
                    if (tempe[i] == "1") {
                        normal = false;
                    }
                    if (i == tempeStatus.length() - 1) {
                        tempeStatus = tempeStatus + inner_number + "-" + tempe[i];
                    }
                }
                for (int i = 0; i < smoke.length; i++) {
                    int inner_number = baseDataInfo.getData().getDeviceInList().get(i).getInner_order();
                    smokeStatus = smokeStatus + inner_number + "-" + smoke[i] + ",";
                    if (smoke[i].equals("1")) {
                        normal = false;
                    }
                    if (i == smokeStatus.length() - 1) {
                        smokeStatus = smokeStatus + inner_number + "-" + smoke[i];
                    }
                }
                //TODO 暂无功能
                eventReportBean.setBin_full_status(fullStatus);//溢满
                eventReportBean.setBin_overweight_status("0-0");//超重
                eventReportBean.setBin_overtemp_status(tempeStatus);//超温
                eventReportBean.setBin_clean_status("0-0");//清理
                eventReportBean.setBin_inspect_status("0-0");//巡检
                eventReportBean.setBin_smoke_status(smokeStatus);
                if (normal == false) {
                    EventBus.getDefault().post("machineError");
                } else if (normal == true) {
                    EventBus.getDefault().post("machineRepair");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return eventReportBean;
    }


    /**
     *
     * @param bD baseDataInfo
     * @param i 第几个投口
     * @return
     */
    public int safe_weightBeangetInnerNumber(BaseDataInfo bD, int i) {
        BaseDataInfo.DataBean dataBean = bD.getData();
        List<BaseDataInfo.DataBean.DeviceInListBean> deviceBeanList = dataBean.getDeviceInList();
        if (deviceBeanList.size() == 0) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "获取设备内桶信息异常，请联系管理员", Toast.LENGTH_SHORT).show();
                }
            });
        }
        BaseDataInfo.DataBean.DeviceInListBean deviceInListBean = deviceBeanList.get(i);
        int inner_number = deviceInListBean.getInner_order();
        return inner_number;
    }


    public void doorOpenStatus(List<String> doorStaus){
        List<Boolean> usingList = new ArrayList<>();
        String[] binarys = new String[DeviceInfo.getMouthQuantity()];
        for(int i = 0; i < DeviceInfo.getMouthQuantity(); i++){
            binarys[i] = doorStaus.get(i);
        }
        //取出维护的list并且判空
        List<BinVO> binVOS = DeviceInfo.getBinVOSList();
        if(binVOS.size() == 0){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,"设备无法获取主板号",Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        for (int i = 0; i < binarys.length; i++) {
            Status status = new Status();
            //代表能开
            if (binarys[i].equals("1")) {
                usingList.add(true);
                status.setType(Status.NORMAL);
            } else if (binarys[i].equals("0")) {
                usingList.add(false);
                status.setType(Status.CANOTOPEN);
            }
            DeviceInfo.setUsingList(usingList);
            DeviceInfo.getBinVOSList().get(i).getBinItemView().setStatus(status);
        }
    }

    public void errorText(List<String> ErrorStatus) {
        String[] binarys = new String[DeviceInfo.getMouthQuantity()];
        for (int i = 0; i < DeviceInfo.getMouthQuantity(); i++) {
            binarys[i] = ErrorStatus.get(i);
        }
        //取出维护的list并且判空
        List<BinVO> binVOS = DeviceInfo.getBinVOSList();
        if(binVOS.size() == 0){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,"设备未注册",Toast.LENGTH_SHORT).show();
                }
            });
        }
        //{01,01,01,01}  解析出了n个值
        for (int i = 0; i < binarys.length; i++) {
            Status status = new Status();
            status.setWeight(2);
            if (binarys[i].equals("01")) {
                status.setType(Status.ERROR);
//                controllerErrorText(i, "1");
                DeviceInfo.getBinVOSList().get(i).setBroken(true);
            } else if (binarys[i].equals("10")) {
                status.setType(Status.ERROR);
//                controllerErrorText(i, "2");
                DeviceInfo.getBinVOSList().get(i).setBroken(true);
            } else if (binarys[i].equals("00")) {
                status.setType(Status.NORMAL);
//                controllerErrorText(i, "0");
            }
            DeviceInfo.getBinVOSList().get(i).getBinItemView().setStatus(status);
        }
    }


    //控制底部Text颜色
    @Deprecated
    public void controllerErrorText(int i, String status) {
        //status 0 正常 1无电流 2过流
        if (status == "1" || status == "2") {
            if (i == 0) {
                tvDustbinOnState.setText("故障");
                tvDustbinOnState.setBackgroundResource(R.drawable.bin_full_status_shape);
            } else if (i == 1) {
                tvDustbinTwoState.setText("故障");
                tvDustbinTwoState.setBackgroundResource(R.drawable.bin_full_status_shape);
            } else if (i == 2) {
                tvDustbinThreeState.setText("故障");
                tvDustbinThreeState.setBackgroundResource(R.drawable.bin_full_status_shape);
            } else if (i == 3) {
                tvDustbinFourState.setText("故障");
                tvDustbinFourState.setBackgroundResource(R.drawable.bin_full_status_shape);
            }
        }
    }


    //设置文本状态Text
    public void warnText(String fullInfo,String tempeInfo,String smokeInfo) { //10000000 代表8个桶子

        String[] fullBinarys = new String[DeviceInfo.mouthQuantity];//按照投口个数设置解析个数
        String[] tempBinarys = new String[DeviceInfo.mouthQuantity];
        String[] smokeBinarys = new String[DeviceInfo.mouthQuantity];//按照投口个数设置解析个数
        for (int i = 0; i < DeviceInfo.mouthQuantity; i = i + 1) { //4次
            fullBinarys[i] = fullInfo.substring(i,i+1);
        }
        for (int i = 0; i < DeviceInfo.mouthQuantity; i = i + 1) {
            tempBinarys[i] = tempeInfo.substring(i,i+1);
        }
        for (int i = 0; i < DeviceInfo.mouthQuantity; i = i + 1) {
            smokeBinarys[i] = smokeInfo.substring(i,i+1);
        }
        //判断是否联网成功
        if(DeviceInfo.getBinVOSList().size() == 0){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this,"设备联网异常,请联系管理员。",Toast.LENGTH_SHORT).show();
                }
            });
            return;
        }

        //Binarys={1,0,0,0}/{1,0,0,0,0}
        //处理溢满
        /**
         * 有warn 不normal
         * 有error 不warn 不normal
         */
        for(int i = 0; i < DeviceInfo.getBinVOSList().size(); i++){ //2次确认数量使用 BinVOSList的数量处理UI
            BinVO thisbin = DeviceInfo.getBinVOSList().get(i);
            /**
             *  刷新状态的状态量
             *  存在异常则必异常，正常则看是否是full状态，如果是full状态则给置，否则不允许置为normal
             *  0为正常，允许置为绿色，1为异常  2为已满
             *  00 正常 01 已满
             *  如果
             */
            int controlVal = -1;
            Status status = new Status();
            if(thisbin.getBroken() == true){//broken代表此时状态写死不应改变 warn代表 成为warn状态
                continue;
            }
            //溢满
            if(fullBinarys[i].equals("1")){
                controlVal = 2;
                status.setStatus(Status.warn_full);
//                thisbin.getBinItemView().setStatus(status);
            }else if(fullBinarys[i].equals("0") && DeviceInfo.getUsingList().get(i)){//只有是启用的桶子才能变成变动
                //只有溢满警报才能恢复 其他警报不能恢复
                controlVal = 0;
                status.setStatus(Status.normal_not_full);
            }else if(fullBinarys[i].equals("0") && !DeviceInfo.getUsingList().get(i)){//如果是未启用
                controlVal = 3;
                status.setStatus(Status.normal_cannot_oepn);
            }
            //一旦出现问题，必然要重启
            //处理温度
            if(tempBinarys[i].equals("1")){
                thisbin.setBroken(true);
                controlVal = 1;
                status.setStatus(Status.warn_over_temperature);
//                status.setType(Status.WARN);
//                status.setStatus(Status.warn_over_temperature);
//                thisbin.getBinItemView().setStatus(status);
//                MyApplication.getBinVOSList().get(i).setBroken(true);
            }
            //处理烟雾
            if(smokeBinarys[i].equals("1")){
                //当其中一个出现烟雾之后，则全部出现烟雾
                for(int j = 0; j < smokeBinarys.length;j++){
                    smokeBinarys[j] = "1";
                }
                thisbin.setBroken(true);
                controlVal = 1;
                status.setStatus(Status.warn_smoke);
//                status.setStatus(Status.warn_smoke);
//                status.setType(Status.WARN);
//                thisbin.getBinItemView().setStatus(status);
//                MyApplication.getBinVOSList().get(i).setBroken(true);
            }
            if(controlVal == 1){
                status.setType(Status.WARN);
            }else if(controlVal == 0){
                status.setType(Status.NORMAL);
            }else if(controlVal == 2){
                status.setType(Status.FULL);
            }else if(controlVal == 3){
                status.setType(Status.CANOTOPEN);
            }
            //送handler 更新此桶子的状态
            sendMsg2SetStatusImg(i,status.getType());
        }
    }

    //设置溢满状态图片
    @Deprecated
    public void warnInfoUpload(String[] warnInfo) {
        String fullStatus = warnInfo[0];
        String temperatureStatus = warnInfo[1];
        String smokeStatus = warnInfo[2];

        if (fullStatus.charAt(0) == '1') {
            tvDustbinOnState.setBackgroundResource(R.drawable.bin_full_status_shape);
        } else if (fullStatus.charAt(0) == '0') {
            tvDustbinOnState.setBackgroundResource(R.drawable.bin_status_shape);
        }

        if (fullStatus.charAt(1) == '1') {
            tvDustbinTwoState.setBackgroundResource(R.drawable.bin_full_status_shape);
        } else if (fullStatus.charAt(1) == '0') {
            tvDustbinTwoState.setBackgroundResource(R.drawable.bin_status_shape);
        }

        if (fullStatus.charAt(2) == '1') {
            tvDustbinThreeState.setBackgroundResource(R.drawable.bin_full_status_shape);
        } else if (fullStatus.charAt(2) == '0') {
            tvDustbinThreeState.setBackgroundResource(R.drawable.bin_status_shape);
        }

        if (fullStatus.charAt(3) == '1') {
            tvDustbinFourState.setBackgroundResource(R.drawable.bin_full_status_shape);
        } else if (fullStatus.charAt(3) == '0') {
            tvDustbinFourState.setBackgroundResource(R.drawable.bin_status_shape);
        }
    }

    /**
     * 发送handler的message到handler修改UI
     */
    private void sendMsg2SetStatusImg(int index,int type){
        Bundle bundle = new Bundle();
        bundle.putInt("index",index);
        bundle.putInt("type",type);
        Message message = Message.obtain();
        message.setData(bundle);
        message.what=300006;
        handler.sendMessage(message);
    }

    private void setBinItemsImageStatus() throws ParserConfigurationException {
        int amount = 0;
        boolean offline = false;
        //断网情况
        if(baseDataInfo == null ){
            Integer count = getBinNum(getApplicationContext());
            ArrayList<BaseDataInfo.DataBean.DeviceInListBean> beanList = new ArrayList<>();
            //生成BinVOList以及视图
            for(int i = 0; i < count ; i++){
                BaseDataInfo.DataBean.DeviceInListBean deviceInListBean = new BaseDataInfo.DataBean.DeviceInListBean();
                String picURL = "https://www.ai-dustbin.com/group1/M00/00/01/rBlUB2E8RxOAaeZmAAI8fMc64XM851.jpg";
                deviceInListBean.setPicUrl(picURL);
                deviceInListBean.setDevice_id(0);
                deviceInListBean.setDiviceIntypeName("普通垃圾");
                deviceInListBean.setId(0);
                deviceInListBean.setStatus_code(6);
                deviceInListBean.setInner_order(i);
                beanList.add(deviceInListBean);
                offline = true;
            }
            //从这里获取amount
            amount = getApplicationContext().getResources().getInteger(R.integer.mouthCount);
            BaseDataInfo.DataBean dataBean = new BaseDataInfo.DataBean();
            dataBean.setDeviceInList(beanList);
            baseDataInfo = new BaseDataInfo();
            baseDataInfo.setData(dataBean);
            showToast("网络连接失败，请联系管理员");
        }else {
            amount = baseDataInfo.getData().getDeviceInList().size();
        }

        List<BinVO> binVOS = new ArrayList<>();
        deleteAllBin();
        for(int i = 0; i < amount ; i++){
            //设置样式和图片这些基本属性
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT);
            if(amount == 5){
                lp.topMargin = 50;
            }
            lp.bottomMargin = 100;
            lp.weight = 1;
            BinVO binVO = generateBinVO(baseDataInfo.getData().getDeviceInList().get(i),i);  //设置binVo的图片和设置Status
            if(binVO == null)
                break;
            binVOS.add(binVO);
            BinItemView binItemView = binVO.getBinItemView();
            if(amount == 5){
                switch (i){
                    case 0:
                        binItemView.setCoinsText("纸类80积分/kg");
                        break;
                    case 1:
                        binItemView.setCoinsText("塑料120积分/kg");
                        break;
                    case 2:
                        binItemView.setCoinsText("金属300积分/kg");
                        break;
                    case 3:
                        binItemView.setCoinsText("玻璃20积分/kg");
                        break;
                    case 4:
                        binItemView.setCoinsText("织物160积分/kg");
                        break;
                }
            }else if(amount == 4){
                binItemView.setCoinsText("");
            }
            binItemView.setLayoutParams(lp);
            dustbinParent.addView(binVO.getBinItemView());
            //创建View之前可以在此处设置，创建view之后想更改view的内容需要在handler或者UI线内
        }
        DeviceInfo.setBinVOSList(binVOS);
    }


    /******************************************************************方法区**********************************************************************************/

    /**
     * 登录后改变UI
     */
    private void loginUI(){
        rlLoginInput.setVisibility(View.GONE);
        rlLoginTip.setVisibility(View.GONE);
        log_out_btn.setVisibility(View.VISIBLE);
        rlMoneyAndCount.setVisibility(View.VISIBLE);
        tvMoney.setText(loginBean.getData().getUserInfo().getUserMoney() + "");
        tvCount.setText(loginBean.getData().getUserInfo().getUserCount() + "");
        tvLoginState.setText(loginBean.getData().getUserInfo().getUserNick() + "");
        tvHeadState.setText("已登录");
        tvHeadState.setBackground(getResources().getDrawable(R.drawable.login_button_shape));
        String url = "https://img2.baidu.com/it/u=1549678844,2900795818&fm=26&fmt=auto&gp=0.jpg";
//        Glide.with(getApplicationContext()).load(loginBean.getData().getUserInfo().getUserHead()).into(iv_headportrait);
    }

    /**
     * 模拟登录
     */
    private void fakeLogin(){
        dustbinStatusControl.loginNotice();//登录成功 通知底层
        rlLoginInput.setVisibility(View.GONE);
        rlLoginTip.setVisibility(View.GONE);
        log_out_btn.setVisibility(View.VISIBLE);
        rlMoneyAndCount.setVisibility(View.VISIBLE);
        LoginBean.DataBean dataBean = new LoginBean.DataBean();
        LoginBean.DataBean.UserInfoBean userInfoBean = new LoginBean.DataBean.UserInfoBean();
        dataBean.setCustomerId("55132165321");
        userInfoBean.setUserMoney(25.5);
        userInfoBean.setUserCount(35);
        userInfoBean.setUserNick("4225525014");
        dataBean.setUserInfo(userInfoBean);
        loginBean = new LoginBean();
        loginBean.setData(dataBean);
        tvMoney.setText(loginBean.getData().getUserInfo().getUserMoney() + "");
        tvCount.setText(loginBean.getData().getUserInfo().getUserCount() + "");
        tvLoginState.setText(loginBean.getData().getUserInfo().getUserNick() + "");
        tvHeadState.setText("已登录");
        tvHeadState.setBackground(getResources().getDrawable(R.drawable.login_button_shape));
        String url1 = "https://img2.baidu.com/it/u=1549678844,2900795818&fm=26&fmt=auto&gp=0.jpg";
        Glide.with(getApplicationContext()).load(url1).into(iv_headportrait);
        if (haveLogin == false) {
            timer.startTimer();
        }
        haveLogin = true;
        DeviceInfo.customerId = loginBean.getData().getCustomerId();
        playHeadMedia();
    }

    //显示Toast
    private void showToast(final String content){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,content,Toast.LENGTH_SHORT).show();
            }
        });
    }

    //获取配置文件中设置的内桶数量
    private Integer getBinNum(Context context) throws ParserConfigurationException {
        Integer num = context.getResources().getInteger(R.integer.mouthCount);
        return num;
    }

    //删除所有子控件
    private void deleteAllBin(){
        int count = dustbinParent.getChildCount();
        if(count > 0){
            dustbinParent.removeAllViews();
        }
    }

    //通过16进制得到满的二进制
    public String[] getRealBinary(String hex) { //过来是10000000
//        String res = hex.substring(0, 1);
//        String tempHex = String.valueOf(DataUtils.HexToInt(res)); //A 10 B 11 C 12 D 13 E 14 F 15
//        String realBinary = Integer.toBinaryString(Integer.parseInt(tempHex));
//        realBinary = StringUtil.logicRight(realBinary, 4);

        String[] binarys = new String[DeviceInfo.getMouthQuantity()]; //4个
        for (int i = 0; i < DeviceInfo.getMouthQuantity(); i = i + 1) {
            binarys[i] = hex.substring(i*2,2*(i+1));
        }
        return binarys;
    }

    public static class GPSEntity {
        Double longitude;
        Double latitude;

        public Double getLongitude() {
            return longitude;
        }

        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        public Double getLatitude() {
            return latitude;
        }

        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }
    }



    private void setoriginBinGone(){
        binCombination1.setVisibility(View.GONE);
        binCombination2.setVisibility(View.GONE);
        binCombination3.setVisibility(View.GONE);
        binCombination4.setVisibility(View.GONE);
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        Log.e("MainActivityRun","OnStop");
        super.onStop();
    }

    /**
     * 重启APP
     */
    private void reLoadApp(){
        Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        intent.putExtra("REBOOT","reboot");
        PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC,System.currentTimeMillis()+1000,restartIntent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 带数据重启
     */
    private void reloadAPPwithData(){
        Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//与正常页面跳转一样可传递序列化数据,在Launch页面内获得
        intent.putExtra("REBOOT","reboot");
        startActivity(intent);
    }


    /****************************************************以下是类区******************************************/
    public GPSEntity GPSUtil(Context context) {
        String locationProvider = null;
        locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = locationManager.getProviders(true);
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
            locationProvider = LocationManager.GPS_PROVIDER;
        } else {
            Log.d("no", "无可用位置提供器");
            return null;
        }
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                gpsEntity.setLatitude(location.getLatitude());
                Log.e("la",gpsEntity.latitude.toString());
                gpsEntity.setLongitude(location.getLongitude());
                Log.e("lo",gpsEntity.longitude.toString());
                handler.sendEmptyMessage(300005);
                locationManager.removeUpdates(this);
            }
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.d("noQ","无权限");
            return null;
        }
        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
        return gpsEntity;
    }

    private void loginstatus2Logout(){
        loginStatus = -1;
        haveLogin = false;
        noIdhaveLogin = false;
    }
    private void loginStatus2HaveIdLogin(){
        loginStatus = 0;
        haveLogin = true;
        noIdhaveLogin = false;
    }
    private void loginStatus2NoIdLogin(){
        loginStatus = 0;
        noIdhaveLogin = true;
        haveLogin = false;
    }

    private void noIdLoginUI(){
        log_out_btn.setVisibility(View.VISIBLE);
        rlLoginTip.setVisibility(View.GONE);
        rlLoginInput.setVisibility(View.VISIBLE);
        needIdLayout.setVisibility(View.GONE);
    }



    class takephotoController{
        private void takephoto(){

        }
    }


}
